import type { KatexOptions } from 'katex'
import { renderToString } from 'katex'

const delimiters = [
  { left: '$$', right: '$$', display: true },
  { left: '$', right: '$', display: false },
  { left: '\\(', right: '\\)', display: false },
  { left: '\\[', right: '\\]', display: true },
  { left: '\\begin{equation}', right: '\\end{equation}', display: true },
  { left: '\\begin{align}', right: '\\end{align}', display: true },
  { left: '\\begin{alignat}', right: '\\end{alignat}', display: true },
  { left: '\\begin{gather}', right: '\\end{gather}', display: true },
  { left: '\\begin{CD}', right: '\\end{CD}', display: true }
]

const autoRenderOptions = {
  delimiters,
  throwOnError: false,
  ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] as const,
  ignoredClasses: ['no-katex']
}

const inlineKatexOptions: KatexOptions = {
  displayMode: false,
  throwOnError: false
}

/**
 * 自动渲染容器内的 LaTeX 数学公式
 * @param container - 需要渲染的 DOM 容器
 */
export const initMath = async (container?: HTMLElement | null) => {
  if (!container?.isConnected) return

  try {
    const { default: katexRender } = await import('katex/contrib/auto-render')
    katexRender(container, autoRenderOptions)
  } catch (error) {
    console.warn('KaTeX render failed:', error)
  }
}

/**
 * 将 LaTeX 表达式渲染为内联 HTML 字符串
 * @param expression - LaTeX 表达式
 * @param options - KaTeX 渲染选项
 * @returns 渲染后的 HTML 字符串
 */
export const renderInline = (expression: string, options?: KatexOptions) => {
  try {
    return renderToString(expression, { ...inlineKatexOptions, ...options })
  } catch (error) {
    console.warn('KaTeX render failed:', error)
    return expression
  }
}
